/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sunspotworld;

import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import java.io.IOException;
import javax.microedition.io.Connector;

/**
 *
 * @author Tomas Henriquez, Sabin Larrañaga
 */
public class Server extends Thread {

    private Radiogram rrg;
    private StartApplication app;
    private RadiogramConnection robotConn;
    private RadiogramConnection reportConn;
    private Radiogram xrg;

    public Server(StartApplication app, RadiogramConnection conn) {
        this.app = app;
        robotConn = conn;
    }

    private void ledlife(int life, ITriColorLED[] leds) {

        for (int i = 0; i < leds.length; i++) {
            leds[i].setOff();
            leds[i].setRGB(0, 0, 30);
        }

        switch (life) {

            case (8):
                leds[7].setOn();

            case (7):
                leds[6].setOn();

            case (6):
                leds[5].setOn();

            case (5):
                leds[4].setOn();

            case (4):
                leds[3].setOn();

            case (3):
                leds[2].setOn();

            case (2):
                leds[1].setOn();

            case (1):
                leds[0].setOn();
        }

    }

    private void reportLife() throws IOException {
        xrg.reset();
        xrg.writeInt(app.getLife());
        reportConn.send(xrg);
    }

    public void run() {
     boolean death = false;
        ledlife(app.getLife(), app.leds);
        //RadiogramConnection conn = null;

        try {
            reportConn = (RadiogramConnection)Connector.open("radiogram://broadcast:" + StartApplication.SERVER_PORT);
            xrg = (Radiogram)reportConn.newDatagram(reportConn.getMaximumLength());
            rrg = (Radiogram) robotConn.newDatagram(robotConn.getMaximumLength());
            reportLife();

            while(app.getLife() > 0){
                rrg.reset();
                robotConn.receive(rrg);
                death = rrg.readBoolean();
                if (death) {
                    app.setLife(app.getLife() - 1);
                    ledlife(app.getLife(), app.leds);
                    reportLife();
                }
            }
            app.notifyDestroyed();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if (reportConn != null) {
            try {
                reportConn.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
